package com.cskaoyan.controller;

import com.cskaoyan.ValidationUtil;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.validation.User;
import com.cskaoyan.exception.ValidationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author stone
 * @date 2022/09/08 10:12
 */
@RestController
public class ValidationController {


    //localhost:8083/valid?username=songge&password=niupi
    @RequestMapping("valid")
    public BaseRespVo valid(@Valid User user) {

        // 正式的业务代码
        return BaseRespVo.ok(null);
    }
    //localhost:8083/valid2?username=songge&password=niupi
    /*@RequestMapping("valid2")
    public BaseRespVo valid2(@Valid User user, BindingResult bindingResult) {

        if (bindingResult.hasFieldErrors()) {// 校验是否通过，如果没通过，这个方法返回值为true
            FieldError fieldError = bindingResult.getFieldError(); //拿到校验错误的成员变量以及对应的错误信息
            String field = fieldError.getField();// 成员变量名 → 请求参数名
            Object rejectedValue = fieldError.getRejectedValue();// 错误的值
            String defaultMessage = fieldError.getDefaultMessage();// 错误的message的信息
            StringBuffer sb = new StringBuffer();
            sb.append("请求参数").append(field).append("传入了错误的值").append(rejectedValue)
                    .append(":").append(defaultMessage);
            return BaseRespVo.invalidParameter(sb.toString());
        }

        // 正式的业务代码
        return BaseRespVo.ok(null);
    }*/

    /*@RequestMapping("valid2")
    public BaseRespVo valid2(@Valid User user, BindingResult bindingResult) {

        BaseRespVo sb = ValidationUtil.getBaseRespVo(bindingResult);
        if (sb != null) return sb;

        // 正式的业务代码
        return BaseRespVo.ok(null);
    }*/

    @RequestMapping("valid2")
    public BaseRespVo valid2(@Valid User user, BindingResult bindingResult) throws ValidationException {

        ValidationUtil.valid(bindingResult);//AspectJ

        // 正式的业务代码
        return BaseRespVo.ok(null);
    }

}
